﻿using System;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Text;
using kysec.RAL.EFToMySql;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace kysec.BLL.Production
{
    /// <summary>
    /// 产品操作类
    /// </summary>
    public class products
    {
        /// <summary>
        /// 添加产品信息，返回成功信息
        /// </summary>
        /// <param name="model">数据集</param>
        /// <returns>0：添加失败 1：添加成功 2：添加异常</returns>
        public static string AddProduct(int type,tb_product model)
        {
            string result = "0";

            Guid id = Guid.Parse(kysec.CR.Common.EncodeByBase64.Decode(HttpContext.Current.Session["userId"].ToString()));
            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            XElement xe=new XElement ("root");
            try
            {
                tb_product product = new tb_product {
                    c_uq_userId = id.ToString(),
                    c_uq_pId = Guid.NewGuid().ToString(),
                    c_i_type = type,
                    c_b_isDemo = false,
                    c_dt_sendTime = DateTime.Now,
                    c_vc_name = model.c_vc_name,
                    c_vc_pModel = model.c_vc_pModel,
                    c_ntx_summary = model.c_ntx_summary,
                    c_ntx_pFeatures=model.c_ntx_pFeatures,
                    c_vc_pFunction=model.c_vc_pFunction,
                    c_vc_subType = model.c_vc_subType,
                    c_x_imgPath = xe.ToString(),
                    c_b_isDelete = false
                };
                ctx.AddObject("tb_product", product);
                result = ctx.SaveChanges().ToString();
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t插入产品信息时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(products), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }

        /// <summary>
        /// 添加产品图片
        /// </summary>
        /// <param name="id">需要增加图片的产品id加密的</param>
        /// <returns>0：添加失败 1：添加成功 2：添加异常</returns>
        public static string addImg(string id,string imgPath)
        {
            string result = "0";

            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            id = kysec.CR.Common.EncodeByBase64.Decode(id);
          
            try
            {
                XElement xe=new XElement("root");
                xe = StringToXe(imgPath);
                var list = ctx.tb_product.Where(c => c.c_uq_pId.Equals(id) && c.c_b_isDelete == false).ToList();

                if (list.Count == 0)
                    result = "0";
                else
                {
                    foreach (var item in list)
                    {
                        item.c_x_imgPath = xe.ToString();
                    }
                    result = ctx.SaveChanges().ToString();
                }
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t添加产品图片时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(products), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }

        public static XElement StringToXe(string imgPath)
        {
            XElement xe = new XElement("Root");
            MatchCollection matchs = Regex.Matches(imgPath, @"<img([^\/>]+)src=""([^""]+)""([^\/>]+)\/>", RegexOptions.IgnoreCase);
            string imgurl = "";
            //if (matchs.Count > 0)
            //{
            //    Match imga = matchs[0];
            //}
            foreach (Match imga in matchs)
            {
                imgurl = imga.Groups[2].Value;


                xe.Add(new XElement("item",new XAttribute("url", imgurl)));
                
            }
            return xe;
        }

        /// <summary>
        /// 实现对XML文件的解析
        /// </summary>
        /// <param name="xe"></param>
        /// <returns>返回string类型</returns>
        public static string AnalyticalXML(string id)
        {
            XElement xe = new XElement(kysec.BLL.Production.Search.getProducts(id)[0].c_x_imgPath);

            if (xe == null)
                return null;
            var xelist = xe.Elements("item").ToList();
            StringBuilder sb = new StringBuilder();

            sb.Append("[");
            int length = xelist.Count();
            for (var x = 0; x < length; x++)
            {
                sb.Append("{url:'");
                sb.Append(xelist[x].Attribute("url").Value.Replace("%Root%", kysec.CR.MyUrl.WebData.WEBURL));
                sb.Append("'}");
                if (x != length - 1)
                {
                    sb.Append(",");
                }
            }
            sb.Append("]");
            return sb.ToString();
        }

        /// <summary>
        /// 设置或取消为样品演示
        /// </summary>
        /// <param name="id">需要设置的产品的信息Id</param>
        /// <returns>0：设置失败 1：设置成功 2：发生异常</returns>
        public static string setDemo(string id,bool isDemo)
        {
            string result = "0";

            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            id = kysec.CR.Common.EncodeByBase64.Decode(id);
            try
            {
                var list = ctx.tb_product.Where(c => c.c_uq_pId.Equals(id) && c.c_b_isDelete == false).ToList();

                if (list.Count == 0)
                    result = "0";
                else
                {
                    foreach (var item in list)
                    {
                        if (isDemo)
                            item.c_b_isDemo = true;
                        else 
                            item.c_b_isDemo = false;
                    }
                    result = ctx.SaveChanges().ToString();
                }
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t设置为样品时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(products), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }

        /// <summary>
        /// 添加样品信息
        /// </summary>
        /// <param name="newsId">需要添加的产品的id</param>
        /// <param name="model">数据集</param>
        /// <returns>0：信息不存在或修改失败 1：修改成功 2：修改异常</returns>
        public static string AddDemo(string id, tb_product model,string imgPath)
        {
            string result = "0";

            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            id = kysec.CR.Common.EncodeByBase64.Decode(id);
            try
            {
                XElement xe=new XElement ("root");
                xe = StringToXe(imgPath);
                var list = ctx.tb_product.Where(c => c.c_uq_pId.Equals(id) && c.c_b_isDelete == false).ToList();

                if (list.Count == 0)
                    result = "0";
                else
                {
                    foreach (var item in list)
                    {
                        item.c_x_imgPath = xe.ToString();
                        item.c_b_isDemo = true;
                        
                    }
                    result = ctx.SaveChanges().ToString();
                }
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t添加样品信息时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(products), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }

        /// <summary>
        /// 修改产品信息
        /// </summary>
        /// <param name="newsId">需要修改的产品的id</param>
        /// <param name="model">数据集</param>
        /// <returns>0：信息不存在或修改失败 1：修改成功 2：修改异常</returns>
        public static string UpdateProduct(string id, tb_product model)
        {
            string result = "0";

            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            id = kysec.CR.Common.EncodeByBase64.Decode(id);
            try
            {
                var list = ctx.tb_product.Where(c => c.c_uq_pId.Equals(id) && c.c_b_isDelete == false).ToList();

                if (list.Count == 0)
                    result = "0";
                else
                {
                    foreach (var item in list)
                    {
                        item.c_vc_name = model.c_vc_name;
                        item.c_vc_pModel = model.c_vc_pModel;
                        item.c_i_type = model.c_i_type;
                        item.c_ntx_pFeatures = model.c_ntx_pFeatures;
                        item.c_vc_pFunction = model.c_vc_pFunction;
                        item.c_ntx_summary = model.c_ntx_summary;
                        item.c_vc_subType = model.c_vc_subType;
                    }
                    result = ctx.SaveChanges().ToString();
                }
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t修改信息时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(products), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }

        /// <summary>
        /// 删除产品，可以同时恢复删除的产品
        /// </summary>
        /// <param name="newsId">需要删除的产品的Id</param>
        /// <returns>0：没有找到信息或删除失败 1：删除成功 2：删除异常</returns>
        public static string DeleteProduct(string id)
        {
            string result = "0";
            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            id = kysec.CR.Common.EncodeByBase64.Decode(id);
            try
            {
                var list = ctx.tb_product.Where(c => c.c_uq_pId.Equals(id)).ToList();

                if (list.Count == 0)
                    result = "0";
                else
                {
                    foreach (var item in list)
                    {
                        if (item.c_b_isDelete)
                            item.c_b_isDelete = false;
                        else
                            item.c_b_isDelete = true;
                    }
                    result = ctx.SaveChanges().ToString();
                }
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t删除信息时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(products), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }
    }
}